package com.example.demo33.service;

import com.example.demo33.entity.InviteCode;
import com.example.demo33.entity.User;
import com.example.demo33.mode.InviteCodeRepository;
import com.example.demo33.mode.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private InviteCodeRepository inviteCodeRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public void registerUser(String username, String password, String inviteCode) {
        // 校验邀请码
/*        InviteCode code = inviteCodeRepository.findByCode(inviteCode)
                .orElseThrow(() -> new RuntimeException("邀请码无效"));
        if (Boolean.TRUE.equals(code.getUsed())) {
            throw new RuntimeException("邀请码已被使用");
        }*/

        // 创建用户
        if (userRepository.existsByUsername(username)) {
            throw new RuntimeException("用户名已存在");
        }
        
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        userRepository.save(user);

/*        // 更新邀请码状态
        code.setUsed(true);
        inviteCodeRepository.save(code);*/
    }

    public Long getUserIdByUsername(String username) {
        User user = userRepository.findByUsername(username)
                .orElse(null);
        return user != null ? user.getId() : null;
    }
}